<?php

namespace frontend\modules\content;

use backend\modules\categories\models\Categories;
use frontend\models\Menu;
use frontend\modules\content\models\Content;
use Yii;

/**
 * content module definition class
 */
class Module extends \yii\base\Module
{
    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();
        $this->setViewPath('@frontend' . Yii::$app->view->theme->baseUrl . '/mod_' . $this->id);
        // custom initialization code goes here
    }

    public function creatUrl($route, $params)
    {
        switch ($route) {
            case '/default/index':
                $category = Categories::findOne($params['cid']);
                if ($category) {
                    $rule = [
                        'pattern' => '_' . $category->path,
                        'route' => $this->id . $route,
                        'defaults' => [
                            'cid' => $params['cid']
                        ]
                    ];
                } else {
                    $rule = [
                        'pattern' => '__category/<cid:\d+>',
                        'route' => $this->id . $route
                    ];
                }
                break;
            case '/default/view':
                $rule = [
                    'pattern' => '__article/<id:\d+>',
                    'route' => $this->id . $route
                ];
                if (isset($params['id'])) {
                    $content = Content::findOne($params['id']);
                    if ($content) {
                        $category = Categories::findOne($content->catid);
                        if ($category) {
                            $rule = [
                                'pattern' => '_' . $category->path . '/<id:\d+>',
                                'route' => $this->id . $route
                            ];
                            if (isset($params['mid'])) {
                                $menu = Menu::findOne($params['mid']);
                                if ($menu) {
                                    $rule = [
                                        'pattern' => $menu->path.'/<id:\d+>',
                                        'route' => $this->id . $route,
                                        'defaults' => ['mid' => $params['mid']]
                                    ];
                                }
                            }
                        }
                    }
                }
                break;
            default:
                $rule = [
                    'pattern' => '__' . basename($route),
                    'route' => $this->id . $route
                ];
                break;
        }
        return $rule;
    }
}
